package com.ncloud.crm.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.MessageBoxEnum;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.MsgBox;
import com.ncloud.crm.mapper.MsgBoxMapper;
import com.ncloud.crm.service.MsgBoxServer;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.param.service.SequenceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by shiqiang on 2017/7/7.
 */
@Service
public class MsgBoxServerImpl implements MsgBoxServer {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MsgBoxMapper msgBoxMapper;
    @Reference
    private SequenceService sequenceService;
    @Override
    public void insertMsg(MsgBox msgBox) {
        if(msgBox.getMsgId()==null){
            Long id = sequenceService.getSequence("seq_msg_box_id");
            msgBox.setMsgId(id);
        }
        msgBoxMapper.insertMessage(msgBox);
    }

    @Override
    public void insertMsgUser(MsgBox msgBox) {
        msgBoxMapper.insertUserMsg(msgBox);
    }

    @Override
    public List<MsgBox> getUserMsg(Long userId) {
        return msgBoxMapper.getMsgUsers(userId);
    }

    @Override
    @Transactional
    public void insertMsgAndUserInfo(JSONObject msg, List<Long> users) {
        logger.debug("msg info{}="+msg.toJSONString());
        Date currentItme = new Date();
          /*id*/
        Long id = sequenceService.getSequence("seq_msg_box_id");
        //logger.info(userId+"");
        MsgBox msgBox = JSON.parseObject(msg.toJSONString(), MsgBox.class);
        msgBox.setMsgId(id);
        msgBox.setCreateTime(currentItme);
          /*1、messgae*/
        msgBoxMapper.insertMessage(msgBox);
          /*2、user*/
        if(users !=null){
            for(Long userId:users){
                msgBox.setUserId(userId);
                msgBox.setMsgState(Constant.MSG_STATE_UNREAD);
                msgBoxMapper.insertUserMsg(msgBox);
            }
        }
    }
}
